//package com.example.shiwu;
//
//import android.annotation.SuppressLint;
//import android.app.AlertDialog;
//import android.content.Context;
//import android.content.DialogInterface;
//import android.content.SharedPreferences;
//import android.content.res.Resources;
//import android.database.Cursor;
//import android.database.sqlite.SQLiteDatabase;
//import android.graphics.Bitmap;
//import android.graphics.BitmapFactory;
//import android.graphics.Color;
//import android.os.Bundle;
//import android.os.Environment;
//import android.os.Handler;
//import android.os.HandlerThread;
//import android.os.Message;
//import android.os.StrictMode;
//import android.view.View;
//import android.widget.ImageView;
//import android.widget.TextView;
//import android.widget.Toast;
//
//import androidx.appcompat.app.AppCompatActivity;
//
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONException;
//import com.alibaba.fastjson.JSONObject;
//import com.chaquo.python.PyObject;
//import com.chaquo.python.Python;
//import com.chaquo.python.android.AndroidPlatform;
//import com.example.shiwu.db.model.Alarm;
//import com.example.shiwu.db.model.Arrange;
//import com.example.shiwu.db.model.Device;
//import com.example.shiwu.db.model.Items;
//import com.example.shiwu.db.model.ReceiveVolEle;
//import com.example.shiwu.db.model.Sends;
//import com.example.shiwu.db.vo.MyQueue;
//import com.example.shiwu.manager.DatabaseHelper;
//import com.example.shiwu.manager.DynamicLineChartManager;
//import com.example.shiwu.service.AlarmService;
//import com.example.shiwu.service.ArrangeService;
//import com.example.shiwu.service.BoxEightService;
//import com.example.shiwu.service.BoxFiveService;
//import com.example.shiwu.service.BoxFourService;
//import com.example.shiwu.service.BoxNineService;
//import com.example.shiwu.service.BoxOneService;
//import com.example.shiwu.service.BoxSevenService;
//import com.example.shiwu.service.BoxSixService;
//import com.example.shiwu.service.BoxTenService;
//import com.example.shiwu.service.BoxThreeService;
//import com.example.shiwu.service.BoxTwoService;
//import com.example.shiwu.service.DeviceService;
//import com.example.shiwu.service.ItemsService;
//import com.example.shiwu.service.ReceiveVolEleService;
//import com.example.shiwu.service.SendsService;
//import com.example.shiwu.util.ArrayUtil;
//import com.example.shiwu.util.ContextVariable;
//import com.example.shiwu.util.DataParseUtil;
//import com.example.shiwu.util.DateUtils;
//import com.example.shiwu.util.FileDownUtil;
//import com.example.shiwu.util.SocketMergeUtils;
//import com.example.shiwu.util.SwitchBoxUtil;
//import com.github.mikephil.charting.charts.BarChart;
//import com.github.mikephil.charting.charts.LineChart;
//
//import java.io.File;
//import java.io.FileNotFoundException;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.net.Socket;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.Timer;
//import java.util.TimerTask;
//
//import cn.hutool.core.util.IdUtil;
//
//public class GatherDataThreadActivity extends AppCompatActivity {
//    private DynamicLineChartManager dynamicLineChartManager;
//    private List<Integer> list = new ArrayList<>(); //数据集合
//    private List<String> names = new ArrayList<>(); //折线名字集合
//    private List<Integer> colour = new ArrayList<>();//折线颜色集合
//    public ImageView title_back, no_data_img;
//    public TextView stop_gather, start_gather, plan_break, permutations, waveform, frequency_spectrum;
//
//    private SharedPreferences.Editor editor;
//    private SharedPreferences preferences;
//    private LineChart plan_break_char;
//    private BarChart bar, arrange_char;
//    private ImageView img;
//
//
//    private Boolean bool1 = true;
//    private int abmn_indx = 0;
//    private Python py;
//    private PyObject pyobj, pyplot, pyobj1, pyobj2, pyobjfft;
//    private static Object lockObject = new Object();
//
//    public JSONArray jsonArray;
//    public byte[] bytesData;
//    public int startCount = 0;
//    public int gatherType = 1;
//    public boolean startPause = false;
//    private OutputStream mOutStream;
//    private InputStream mInStream;
//
//    private HandlerThread mHandlerThread;
//    //子线程中的Handler实例。
//    private Handler mSubThreadHandler;
//
//    private final int STATE_DISCONNECTED = 1;
//    private final int STATE_CONNECTING = 2;
//    private final int STATE_CONNECTED = 3;
//    public int count_byte = 0;
//    private String cmd_index_len = "";//消息的id 10
//    private int success_count = 0;
//    private int header_cou = 0;
//    public String receiveDataAll = "";
//    private Integer packet_indx = 0;
//    private Integer packet_lens = 0;//总包数 1536倒计数到0 packet_lens=0, bak_packet_lens=512, rec_count=512 self.send("kConfirm",rec_count)
//    private int loding_count = 0;
//
//    public Socket mSocket;
//    private final int DEFAULT_PORT = 8086;
//    private String mIpAddress = ContextVariable.IP; //服务端ip地址
//    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
//    private static final String IP_ADDRESS = "ip_address";
//    private static final String CLIENT_PORT = "client_port";
//    private static final String CLIENT_MESSAGETXT = "client_msgtxt";
//    public final int MSG_SUCCESS = 1;
//    public String IPValues = "";
//    private static final int MSG_RECEIVE_DATA = 9;
//    private static final int MSG_RECEIVE_TU_DATA = 10;
//    private static final int MSG_RECEIVE_PAI_DATA = 11;
//    private static final int MSG_RECEIVE_BO_DATA = 12;
//    private static final int MSG_RECEIVE_PIN_DATA = 13;
//    private static final int MSG_RECEIVE_SECTION_DATA = 14;
//    private static final int MSG_RECEIVE_OVER_DATA = 15;
//    private int mSocketConnectState = STATE_DISCONNECTED;
//
//    private SendsService sendsService;
//    private ItemsService itemsService;
//    private ImageView mChart1, mChart2, mChart3, mChart4;
//    private String[] freqData,modeData,freqFilterData;
//    private String permutationMode;//采集模式，加到CVS里
//    private int sf = 0;
//    private ArrangeService arrangeService;
//    private DeviceService deviceService;
//    private List<Arrange> arrangeLis;
//
//    private byte[] byt;
//    private String simpleUUID;
//    private MyQueue queue, queueMsg;
//    private Boolean receive_one_field_sta = true;
//    private String vol_ele = "";
//    private String fileName = "";
//    private String vol_ele_noindx = "";
//    private String str_vol_ele_noindx = "";
//    private int packet_lens_old = 0;
//    private String tx_voltage_data = "";
//    private String tx_current_data = "";
//    private String rx_voltage_data = "";
//    private Integer rx_voltage_data_len = 0;
//    private Integer cvs_line = 0;
//    private boolean back_over = false; //biaoshi
//    private int receive_packet_indx_count = 0;
//    private byte[] buffer = null;
//    private Context myContext;
//    //private SocketUtils socketUtils;
//    private SocketMergeUtils socketUtils;
//    private ReceiveVolEleService receiveVolEleService;
//    private AlarmService alarmService;
//    private Boolean receive_sta = false;//采集一次后true 过滤vol_ele的title
//    private byte[] data, data2, data3;
//    private int msg_sueecss_count = 0;
//    private Boolean startGater = false;
//    private Boolean errorRepeat = false;
//    private long timeouts = 17500;
//    public MyThread myThread;
//    public Boolean returnSta = true;
//    private String dtype, shape, abmn, abmnStr;
//    private int dtypelen, dtypelen0, dtypelenAbmn, ns,abmnLen, boxId, boxInx;;
//    private int inclickGatherCount;//点击采集按钮次数
//    private int packet_indx1 = 0;
//    private TextView send_poiont_val;
//    private TextView receive_poiont_val;
//    private TextView filter_type_val;
//    private TextView device_type_val;
//    private TextView receive_voltage_val;
//    private TextView send_frequency_val;
//    private String freq_Indx, repeatUnm;
//
//    private String[] clearStrLisAll;
//    private Integer rec_count_s = 0;
//
//    private int num_points = 0; // 数据点 （128,258,512）
//    private int filter = 0;//滤波类型 0不滤波 1低频滤波 2阻带滤波
//    private String send_piont="";//发射点
//    private String receive_piont="";//接收点
//    public Boolean recv_float_bool = false;
//    public Boolean recv_float_bool2 = true;
//    private String itemsId;
//    private String rx_voltage_data_all = "";
//    private Boolean bool = false;
//    private String send_frequency_value, send_repeat_value, send_voltage_value;
//    private ArrayList<Double[]> tx_c_rx_v_lis = null;
//    // private JSONObject jb = null;
//    private JSONObject jb_tu = new JSONObject();
//    private JSONObject jsonObjectMsg = new JSONObject();
//    private JSONArray jbA = null;
//    private int[] repate_indx = null;
//    private String jb_tu_str;
//    private DataParseUtil dataParseUtil;
//    private Items items;
//    private StringBuffer rx_voltage_data1;
//    private StringBuffer rx_voltage_data_all1;
//    Boolean errorCount = true;
//    public Boolean anewSta = true;
//    private String[] boxlis = null;
//    private ArrayList<String> alis = null;
//    private ArrayList<String> boxLatLon;
//    private BoxOneService boxOneService;
//    private BoxTwoService boxTwoService;
//    private BoxThreeService boxThreeService;
//    private BoxFourService boxFourService;
//    private BoxFiveService boxFiveService;
//    private BoxSixService boxSixService;
//    private BoxSevenService boxSevenService;
//    private BoxEightService boxEightService;
//    private BoxNineService boxNineService;
//    private BoxTenService boxTenService;
//    private DatabaseHelper dbHelper;
//    public Boolean errorSta = false;
//    public Boolean boolErr = true;
//    private StringBuffer tx_current_data1;
//
//    private Handler mHandler = new Handler() {
//        @SuppressLint("HandlerLeak")
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case MSG_SUCCESS:
//                    img.setImageBitmap(BitmapFactory.decodeByteArray((byte[]) msg.obj, 0, ((byte[]) msg.obj).length));
//                    if (msg.arg1 == 1) {
//                        try {
//                            bytesData = pyobj.callAttr("ERTPlot", jsonArray.get(0).toString(), 0).toJava(byte[].class);
//                            Thread.sleep(100);
//                            img.setImageBitmap(BitmapFactory.decodeByteArray((byte[]) msg.obj, 0, ((byte[]) msg.obj).length));
//                        } catch (InterruptedException e) {
//                            throw new RuntimeException(e);
//                        }
//                    }
//                    break;
//
////                case MSG_SOCKET_CONNECT:
//                // 初始化 SocketUtils，替换成你的服务器地址和端口
//
//                case MSG_RECEIVE_TU_DATA:
//                    //拟断面
//                    planBreak();
//                    int idex = msg.arg1;
//                    String obj1 = (String) msg.obj;
//                    List<byte[]> fio = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex), ns, 0,
//                            obj1, freq_Indx, rx_voltage_data_len, num_points, num_points,filter);
//                    if (fio.size() > 1) {
//                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio.get(1), 0, fio.get(1).length));
//                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio.get(2), 0, fio.get(2).length));
//                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio.get(3), 0, fio.get(3).length));
//                        start_gather.setEnabled(true);
//                        start_gather.setText("采集数据");
//                        myThread.pauseThread();
//                        savebitmap(BitmapFactory.decodeByteArray(fio.get(0), 0, fio.get(0).length), "niduan");
//                        savebitmap(BitmapFactory.decodeByteArray(fio.get(1), 0, fio.get(1).length), "pailie");
//                        savebitmap(BitmapFactory.decodeByteArray(fio.get(2), 0, fio.get(2).length), "boxing");
//                        savebitmap(BitmapFactory.decodeByteArray(fio.get(3), 0, fio.get(3).length), "pinpu");
//                    }
//                    mChart1.setImageBitmap(BitmapFactory.decodeByteArray(fio.get(0), 0, fio.get(0).length));
//
//                    break;
//                case MSG_RECEIVE_PAI_DATA:
//                    //排列图示
//                    permutations();
//                    int idex2 = msg.arg1;
//                    String obj2 = (String) msg.obj;
//                    List<byte[]> fio2 = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex2), ns, 1,
//                            obj2, freq_Indx, rx_voltage_data_len, num_points, num_points,filter);
//                    if (fio2.size() > 1) {
//                        mChart1.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(0), 0, fio2.get(0).length));
//                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(1), 0, fio2.get(1).length));
//                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(2), 0, fio2.get(2).length));
//                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(3), 0, fio2.get(3).length));
//                        start_gather.setEnabled(true);
//                        start_gather.setText("采集数据");
//                        myThread.pauseThread();
//                    } else {
//                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(0), 0, fio2.get(0).length));
//
//                    }
//                    break;
//                case MSG_RECEIVE_BO_DATA:
//                    //实时波形
//                    waveform();
//                    String obj3 = (String) msg.obj;
//                    int idex3 = msg.arg1;
//                    List<byte[]> fio3 = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex3), ns, 2,
//                            obj3, freq_Indx, rx_voltage_data_len, num_points, num_points,filter);
//                    if (fio3.size() > 1) {
//                        mChart1.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(0), 0, fio3.get(0).length));
//                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(1), 0, fio3.get(1).length));
//                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(2), 0, fio3.get(2).length));
//                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(3), 0, fio3.get(3).length));
//                        start_gather.setEnabled(true);
//                        start_gather.setText("采集数据");
//                        myThread.pauseThread();
//                    } else {
//                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(0), 0, fio3.get(0).length));
//                    }
//                    break;
//                case MSG_RECEIVE_PIN_DATA:
//                    //频谱
//                    frequencySpectrum();
//                    String obj4 = (String) msg.obj;
//                    int idex4 = msg.arg1;
//                    List<byte[]> fio4 = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex4), ns, 3,
//                            obj4, freq_Indx, rx_voltage_data_len, num_points, num_points,filter);
//                    if (fio4.size() > 1) {
//                        mChart1.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(0), 0, fio4.get(0).length));
//                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(1), 0, fio4.get(1).length));
//                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(2), 0, fio4.get(2).length));
//                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(3), 0, fio4.get(3).length));
//                        start_gather.setEnabled(true);
//                        start_gather.setText("采集数据");
//                        myThread.pauseThread();
//                    } else {
//                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(0), 0, fio4.get(0).length));
//                    }
//                    break;
//
//
//                case MSG_RECEIVE_DATA:
//                    String[] vel = vol_ele.split(";");
//                    //生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
//                    //String simpleUUID = IdUtil.simpleUUID();
//                    FileDownUtil.saveFile(myContext, vel, simpleUUID);
//                    List<ReceiveVolEle> lis = new ArrayList<ReceiveVolEle>();
//                    ReceiveVolEle rve = null;
//                    MyQueue queue1 = new MyQueue();
//                    int ii = 0;
//                    if (!receive_sta) {
//                        ii = 1;
//                    }
//                    for (int i = ii; i < vel.length; i++) {
//                        String vel_new = "";
////                        if (i != 0) {
////                            vel_new = vel[i].substring(1, vel[i].length());
////                        } else {
//
//
//                        vel_new = vel[i];
//                        //}
//                        if (!vel_new.equals("")) {
//                            String[] vel_new_lis = vel_new.split(",");
//                            rve = new ReceiveVolEle();
//                            for (int j = 0; j < vel_new_lis.length; j++) {
//                                switch (j) {
//                                    case 1:
//                                        rve.setIndx(Integer.parseInt(vel_new_lis[j]));
//                                        rve.setCreateTime(DateUtils.parseDate());
//                                        rve.setGropId(simpleUUID);
//                                        Items items = findSelectItem();
//                                        rve.setItemId(items.getId());
//                                        break;
//
//                                    case 7:
//                                        rve.setTxv(vel_new_lis[j]);
//                                        break;
//                                    case 8:
//                                        rve.setTxc(vel_new_lis[j]);
//                                        break;
//
//                                    case 9:
//                                        rve.setRxv(vel_new_lis[j]);
//                                        break;
//                                }
//
//                            }
//                            lis.add(rve);
//                            queue1.enQueue(rve);
//                            ReceiveVolEle rveDo = (ReceiveVolEle) queue1.deQueue();
//                            //queue.clear();
//                            if (rve != null && rve.getIndx() != null) {
//                                receiveVolEleService.save(rve);
//                            }
//                            receive_sta = true;
//                        }
//
//                    }
////
////                    System.out.println("---- thread ="+mConnectThread);
//                    //setImageVal(rx_voltage);
//                    break;
//                case MSG_RECEIVE_OVER_DATA:
//                    Toast.makeText(myContext, "采集数据结束！", Toast.LENGTH_SHORT).show();
//                    try {
//                        Thread.sleep(1000);
//                        //DataParseUtil.ClosePlt();
//                        //socketUtils.releaseSocket();
//                        //socketUtils.stopListening();
//                        startGater = false;
//                        msg_sueecss_count = 0;
//                        SocketMergeUtils.success_count = 0;
//                        start_gather.setText("采集结束");
//                        start_gather.setEnabled(false);
//
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
//                    //GatherDataActivity.this.finish();
//                    break;
////                case MSG_RECEIVE_SECTION_DATA:
////                    displayChart();
////
////                    gatherType = 3;
////                    switch (gatherType) {
////                        case 1:
////                            byte[] io = (byte[]) msg.obj;
////                            mChart1.setVisibility(View.VISIBLE);
////                            mChart1.setImageBitmap(BitmapFactory.decodeByteArray(io, 0, io.length));
////                            break;
////                        case 2:
////                            byte[] io1 = (byte[]) msg.obj;
////                            mChart2.setVisibility(View.VISIBLE);
////                            mChart2.setImageBitmap(BitmapFactory.decodeByteArray(io1, 0, io1.length));
////                            break;
////                        case 3:
//////                            mChart3.setVisibility(View.VISIBLE);
//////                            mChart3.setImageBitmap(BitmapFactory.decodeByteArray(io, 0, io.length));
////                            byte[] fftIos = rx_voltage_data.getBytes();
////                            byte[] data1 = pyobj2.callAttr("draw_fft_square_wave", fftIos, sf, rx_voltage_data_len).toJava(byte[].class);
////                            mChart3.setImageBitmap(BitmapFactory.decodeByteArray(data1, 0, data1.length));
////                            break;
////                        case 4:
//////                            mChart4.setVisibility(View.VISIBLE);
//////                            mChart4.setImageBitmap(BitmapFactory.decodeByteArray(io, 0, io.length));
////                            byte[] data4 = pyobj2.callAttr("draw_fft", "[" + str_vol_ele_noindx + "]", sf, packet_lens / 3).toJava(byte[].class);
////                            mChart1.setImageBitmap(BitmapFactory.decodeByteArray(data4, 0, data4.length));
////                            break;
////                    }
////
////                    break;
//            }
//        }
//    };
//
//
//    public JSONObject initJson() {
//        JSONObject jsonObject = new JSONObject();
//        JSONObject jsonObject2 = new JSONObject();
//        //Items items = null;
//        Arrange arrange = new Arrange();
//        num_points = SocketMergeUtils.packet_lens_old / 3;
//        try {
//            //items = findSelectItem();
//            if (null != items) {
//                arrange.setItemId(items.getId());
//
//                Arrange arrange2 = arrangeLis.get(0);
//                jsonObject.put("num_electrodes", "20");
//                jsonObject.put("Max_n_spacing", "20");
//                jsonObject.put("Aspacing", arrange2.getElectrodeDistance());
//                jsonObject.put("ChnNO", "10");
//                //jsonObject.put("ABMN", abmnStr.replace(",",""));
//                jsonObject.put("ABMN", abmn);
//                jsonObject.put("TXFrq", freq_Indx);
//                jsonObject.put("TXDuty", "10");
//                jsonObject.put("CycleNO", "10");
//                jsonObject.put("StackNO", send_repeat_value);
//                jsonObject.put("RXSR", num_points);
//                jsonObject.put("dtype", arrange2.getDtype());
//                jsonObject.put("shape", arrange2.getShape());
//                //jsonObject.put("path", "/data/data/com.example.shiwu/files/1-9f0a4c7f39674bb68e1b20b0505044c3.cvs");
//                jsonObject2.put("Aspacing", arrange2.getElectrodeDistance());
//                jsonObject2.put("ABMN", abmn);
//                jsonObject2.put("dtype", arrange2.getDtype());
//                jsonObject2.put("shape", arrange2.getShape());
//                ns = dataParseUtil.ERTuiSectionNs(jsonObject2.toString());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return jsonObject;
//    }
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//
//        if (android.os.Build.VERSION.SDK_INT > 9) {
//            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//            StrictMode.setThreadPolicy(policy);
//        }
//        myContext = this;
//        queue = new MyQueue();
//        queueMsg = new MyQueue();
//        dataParseUtil = new DataParseUtil();
//        rx_voltage_data1 = new StringBuffer();
//        rx_voltage_data_all1 = new StringBuffer();
//        deviceService = new DeviceService();
//
//        dbHelper = new DatabaseHelper(this);
//        initService();
//        setContentView(R.layout.activity_gather);
//        mChart1 = findViewById(R.id.imageViews);
//        mChart2 = findViewById(R.id.imageViews2);
//        mChart3 = findViewById(R.id.imageViews3);
//        mChart4 = findViewById(R.id.imageViews4);
//        Resources res = getResources();
//        freqData = res.getStringArray(R.array.freqData);
//        modeData = res.getStringArray(R.array.modeData);
//        freqFilterData = res.getStringArray(R.array.freqFilter);
//        arrangeService = new ArrangeService();
//        receiveVolEleService = new ReceiveVolEleService();
//        alarmService = new AlarmService();
//        items = findSelectItem();
//        rx_voltage_data1 = new StringBuffer();
//        tx_current_data1 = new StringBuffer();
//        boxId =getBoxInx();
////        IPValues = "[{'TXA': 0.0, 'TXB': 20.0, 'RXM': 40.0, 'RXN': 60.0, 'X': 30.0, 'Z': 20.0, 'n': 1.0, 'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 376.99111843077515},{'TXA': 0.0, 'TXB': 20.0, 'RXM': 60.0, 'RXN': 80.0, 'X': 40.0, 'Z': 30.0, 'n': 2.0, 'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 1507.9644737231006}, {'TXA': 0.0, 'TXB': 20.0, 'RXM': 80.0, 'RXN': 100.0, 'X': 50.0, 'Z': 40.0, 'n': 3.0, 'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 3769.9111843077517}, {'TXA': 0.0, 'TXB': 20.0, 'RXM': 100.0, 'RXN': 120.0, 'X': 60.0, 'Z': 50.0, 'n': 4.0, 'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 7539.822368615503}, {'TXA': 0.0, 'TXB': 20.0, 'RXM': 120.0, 'RXN': 140.0, 'X': 70.0, 'Z': 60.0, 'n': 5.0, 'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 13194.689145077129},  {'TXA': 0.0, 'TXB': 20.0, 'RXM': 140.0, 'RXN': 160.0, 'X': 80.0, 'Z': 70.0, 'n': 6.0, 'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 21111.50263212341},{'TXA': 0.0, 'TXB': 20.0, 'RXM': 160.0, 'RXN': 180.0, 'X': 90.0, 'Z': 80.0, 'n': 7.0, 'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 31667.253948185116},{'TXA': 0.0, 'TXB': 20.0, 'RXM': 180.0, 'RXN': 200.0, 'X': 100.0, 'Z': 90.0, 'n': 8.0, 'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 45238.93421169302},{'TXA': 0.0, 'TXB': 20.0, 'RXM': 200.0, 'RXN': 220.0, 'X': 110.0, 'Z': 100.0, 'n': 9.0,'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 62203.534541077905},{'TXA': 0.0, 'TXB': 20.0, 'RXM': 220.0, 'RXN': 240.0, 'X': 120.0, 'Z': 110.0, 'n': 10.0, 'TXI': 2.0,'RXV': 2.0, 'IP': 0.0, 'Rho': 82938.04605477054},{'TXA': 20.0, 'TXB': 40.0, 'RXM': 60.0, 'RXN': 80.0, 'X': 50.0, 'Z': 20.0, 'n': 1.0, 'TXI': 2.0, 'RXV': 2.0, 'IP': 0.0, 'Rho': 376.99111843077515}]";
//
////        preferences = getSharedPreferences("gather", MODE_PRIVATE);
////        editor = preferences.edit();
////        editor.clear().putBoolean("first_stop", true);
////        editor.clear().putBoolean("start_stop", false);
////        // 提交数据
////        editor.commit();
//
////        boolean bl = preferences.getBoolean("first_stop", true);
//        boolean bool = getViewInit();
//
//        title_back.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (startCount == 1) {
//                    AlertDialog.Builder dialog = new AlertDialog.Builder(myContext);//通过AlertDialog.Builder创建出一个AlertDialog的实例
//                    dialog.setTitle("提示");//设置对话框的标题
//                    dialog.setMessage("采集数据中请勿离开页面,否则会中断采集!");//设置对话框的内容
//                    dialog.setCancelable(false);//设置对话框是否可以取消
//                    dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {//确定按钮的点击事件
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            recv_float_bool = false;
//                            receive_one_field_sta = false;
//                            try {
//                                Thread.sleep(100);
//                                GatherDataThreadActivity.this.finish();
//                            } catch (InterruptedException e) {
//                                throw new RuntimeException(e);
//                            }
//
//                        }
//                    });
//                    dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {//取消按钮的点击事件
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                        }
//                    });
//                    dialog.show();//显示对话框
//                } else {
//                    GatherDataThreadActivity.this.finish();
//                }
//            }
//        });
//        plan_break.setTextColor(Color.parseColor("#FF007AFF"));
//        plan_break.setTextSize(18);
//        //arrange_char.setVisibility(View.GONE);
//        //startStopGather();
//
//
////        socketUtils = SocketMergeUtils.getInstance(myContext);
////        if (socketUtils.socket == null) {
////            Toast toast = Toast.makeText(myContext, "网络连接失败！", Toast.LENGTH_SHORT);
////            toast.setGravity(Gravity.CENTER, 0, 0);
////            toast.show();
////            GatherDataActivity.this.finish();
////        } else {
////            socketUtils.releaseSocket();
////        }
////        SocketMergeUtils.success_count = 0;
////        socketListener();
////        myThread = new MyThread();
//
//        start_gather.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                DataParseUtil.ClosePlt();
//                if (socketUtils == null) {
//                    socketUtils = SocketMergeUtils.getInstance(myContext);
//
//                    SocketMergeUtils.success_count = 0;
//                    SocketMergeUtils.receiveDataAll = "";
//                    socketListener();
//                    if (socketUtils.mMainInfoThread != null) {
//                        socketUtils.stopMainInfoListening();
//                    }
//                    if (socketUtils.mAlarmThread != null) {
//                        socketUtils.stopAlarmListening();
//                    }
//
//                } else {
//                    socketListener();
//                }
//                //msg_sueecss_count=0;
//                SocketMergeUtils.success_count = 0;
//
//                myThread = new MyThread();
//
////                try {
////                    Thread.sleep(1000);
////                } catch (InterruptedException e) {
////                    throw new RuntimeException(e);
////                }
//                startCount = 1;
//                start_gather.setText("采集中..");
//                start_gather.setEnabled(false);
//                System.out.println("-------------------采集中---------------");
//                sendsService = new SendsService();
//                itemsService = new ItemsService();
//                Items items = new Items();
//                items.setStatus(1);
//                List<Items> items1 = itemsService.getItems(items);
//                List<Sends> sends = sendsService.getSendsLast(new Sends(items1.get(0).getId()));
//                Arrange arrange1 = new Arrange();
//                arrange1.setItemId(items.getId());
//                arrangeLis = arrangeService.getArrange(arrange1);
//                Boolean boo = sendMcu(sends.get(0), items1.get(0).getId());
//                if (boo) {
//                    simpleUUID = IdUtil.simpleUUID();
//                    saveSends(sends.get(0));
//                }
//
//            }
//        });
//
//        try {
//            initPython(this);
//
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        //loding_count += 1;
//    }
//
////    @Override
////    protected void onStart() {
////        super.onStart();
////        android.os.Process.killProcess(android.os.Process.myPid());
////    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        //退出HandlerThread的Looper循环。
//        System.out.println("---------------------- onDestroy --------------------");
//        //socketUtils.releaseSocket();
//        //socketUtils.stopListening();
//        startGater = false;
//        msg_sueecss_count = 0;
//        SocketMergeUtils.success_count = 0;
//    }
//
//    public int getBoxInx() {
//        Items items = findSelectItem();
//        itemsId = items.getId().toString();
//        Arrange arrange1 = new Arrange();
//        arrange1.setItemId(Integer.valueOf(itemsId));
//        List<Arrange> arrangeLis = arrangeService.getArrange(arrange1);
//        abmnLen = arrangeLis.get(0).deviceTypeLen + 1;
//        Device device = new Device();
//        device.setItemId(itemsId);
//        List<Device> lis = deviceService.getDevice(device);
//        int count = 0;
//        if (lis.size() == 0) {
//            Toast.makeText(myContext, "网络连接失败！", Toast.LENGTH_SHORT).show();
//            //return;
//            count = 0;
//        } else if (lis.size() > 0) {
//            String box = lis.get(0).getBox().replaceAll(" ", "");
//            boxlis = box.split(",");
//            alis = new ArrayList();
//            for (int i = 0; i < boxlis.length; i++) {
//                if (!boxlis[i].equals("00")) {
//                    alis.add(boxlis[i]);
//                }
//            }
//            count = abmnLen / alis.size();
//        }
//
//        return count;
//    }
//    private void socketListener() {
//
//        if (socketUtils != null) {
//            // 启动监听
//            socketUtils.startListening();
//            // 设置消息监听器
//            socketUtils.setOnMessageReceivedListener(new SocketMergeUtils.OnMessageReceivedListener() {
//                @Override
//                public void onMessageReceived(byte message) {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            //System.out.println("======================== socketUtils ================" + socketUtils == null);
//
//                            // 在UI线程更新消息
//                            queue.enQueue(message);
//                        }
//                    });
//                }
//
//                @Override
//                public void onMessageReceivedString(String message) {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//
//
//                            if (errorRepeat) {//出错重复
//                                System.out.println("-------------onMessageReceivedString-出错重复-------------");
////                                Timer timer = new Timer();
////                                TimerTask task = new TimerTask() {
////                                    @Override
////                                    public void run() {
////                                        getTask();
////                                        errorRepeat = false;
////                                    }
////                                };
////                                timer.schedule(task,0,timeouts);
////                                timer.cancel();
//                            }
//                            System.out.println("======================== success or bad_param ================" + message);
//                            if (recv_float_bool == false && recv_float_bool2 == false) {
//                                //System.out.println("======================== myThread.resumeThread()================" );
//                                recv_float_bool = true;
//                                recv_float_bool2 = true;
//                                myThread.resumeThread();
//                            }
//                            if (message.equals("None")) {
//                                System.out.println(" usb/wifi connect error ");
//                                return;
//                            }
//                            if (message.contains("kErrorAlarm")) {//告警写入
//                                System.out.println(" kErrorAlarm================= " + message);
//                                Alarm alarm = new Alarm(itemsId);
//                                alarm.setAlarmMsg(message);
//                                alarmService.save(alarm);
//                                return;
//                            }
//                            if (message.equals("null")) {
//                                if (startCount == 1) {
//                                    Toast.makeText(myContext, "采集数据失败！", Toast.LENGTH_SHORT).show();
//                                }
//                                return;
//                            }
//                            if (message.contains("Success;") && !message.equals("")) {
//                                msg_sueecss_count += 1;
//                                switch (msg_sueecss_count) {
//                                    case 2: //kSetTxWaveWithParam 3
//                                        if (data != null) {
//                                            try {
//                                                Thread.sleep(0);
//                                            } catch (InterruptedException e) {
//                                                throw new RuntimeException(e);
//                                            }
//                                            SocketMergeUtils.writeMsgByte(data);
//                                            System.out.println("-----------kSetTxWaveWithParam 3-------------");
//                                        }
//                                        break;
//                                    case 3://kClearAllMuxBoxConnect 15
//                                        if (data != null) {
//                                            try {
//                                                Thread.sleep(0);
//                                            } catch (InterruptedException e) {
//                                                throw new RuntimeException(e);
//                                            }
//                                            if (data2.length > 0) {
//                                                SocketMergeUtils.writeMsgByte(data2);
//                                                System.out.println("-----------kClearAllMuxBoxConnect 15-------------");
//                                            }
//
//                                        }
//                                        break;
//                                    case 4://kSetMuxBoxConnect 2
//                                        if (data != null) {
//                                            try {
//                                                Thread.sleep(0);
//                                            } catch (InterruptedException e) {
//                                                throw new RuntimeException(e);
//                                            }
//                                            SocketMergeUtils.writeMsgByte(data3);
//                                            System.out.println("-----------kSetMuxBoxConnect 2-------------");
//                                        }
//                                        break;
//                                    case 5:
//                                        if (data != null) {
//                                            try {
//                                                Thread.sleep(0);
//                                            } catch (InterruptedException e) {
//                                                throw new RuntimeException(e);
//                                            }
//                                            String data = "23,r;";
//                                            SocketMergeUtils.writeMsgByte(data.getBytes());
//                                            System.out.println("-----------23,r;-------------");
//                                        }
//                                        break;
//                                    case 6:
//                                        if (data != null) {
//                                            try {
//                                                Thread.sleep(0);
//                                            } catch (InterruptedException e) {
//                                                throw new RuntimeException(e);
//                                            }
//                                            String data1 = "4,start;";
//                                            SocketMergeUtils.success_count = 6;
//                                            SocketMergeUtils.writeMsgByte(data1.getBytes());
//
//                                            System.out.println(" =============== 4,start; 开始= " + DateUtils.parseYmdHmsDate());
//                                            System.out.println(" =============== 4,start; 开始= " + SocketMergeUtils.success_count);
////                                            Timer timer = new Timer();
////                                            TimerTask task = new TimerTask() {
////                                                @Override
////                                                public void run() {
////                                                    getTask();
////                                                    //errorRepeat = true;
////                                                }
////                                            };
////                                            timer.schedule(task,timeouts);
////                                            timer.cancel();
//                                            startGater = true;
//                                            myThread.resumeThread();
//                                        }
//                                        break;
//                                }
//                            } else if (message.equals("0,Timeout;")||message.equals("0,Time_Out;")) {
//                                System.out.println(" kSetMuxBoxConnect switch box connect error ");
//                                Toast.makeText(myContext, "开关盒子连接出错！", Toast.LENGTH_SHORT).show();
//                            } else if (message.equals("0,Bad_Param;")||message.equals("0,BadParam;")) {
//                                System.out.println("======================== bad_param ================" + message);
//                                Toast.makeText(myContext, "ABMN配置错误！", Toast.LENGTH_SHORT).show();
//                            }else if (message.equals("0,alarm;")) {
//                                System.out.println("======================== bad_param ================" + message);
//                                Toast.makeText(myContext, "设备告警！", Toast.LENGTH_SHORT).show();
//                            }
//                        }
//                    });
//                }
//
//                @Override
//                public void onConnectionLost() {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            // 处理连接中断的情况，例如显示提示或重新连接
//                            //handleConnectionLost();
//                            System.out.println(" socket 断开==================================");
//                        }
//                    });
//                }
//            });
//
//
//        }
//    }
//
//
//    class MyThread extends Thread {
//        public final Object lock = new Object();
//        public boolean threadExit;
//
//
//        public MyThread() {
//            threadExit = false;
//        }
//
//        /**
//         * 调用这个方法实现暂停线程
//         */
//        public void pauseThread() {
//            threadExit = true;
//        }
//
//        /**
//         * 调用这个方法实现恢复线程的运行
//         */
//        public void resumeThread() {
//            threadExit = false;
//            synchronized (lock) {
//                lock.notifyAll();
//            }
//        }
//
//        public void threadExit() {
//            threadExit = true;
//        }
//
//        /**
//         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
//         */
//        public void onPause() {
//            synchronized (lock) {
//                try {
//                    lock.wait();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//        @Override
//        public void run() {
//            while (!threadExit) {
//                //tx_c_rx_v_lis.clear();
//                msg_sueecss_count = 1;
//                //returnSta = false;
//                abmnStr = "";
//                if (inclickGatherCount == 0) {
//                    System.out.println("---------------dtypelen2---" + 0);
//                    dtypelenAbmn = 0;
//                    abmnStr = pyobj1.callAttr("subABMN", abmn, dtype, shape, 0).toJava(String.class);
//                    System.out.println("abmnStr =====" + abmnStr);
//                } else {
//                    int dtypelen1 = dtypelen0 - 1;
//                    //System.out.println("---------------dtypelen1---"+dtypelen1);
//                    int dtypelen2 = dtypelen - dtypelen1;
//                    dtypelenAbmn = dtypelen2;
//                    System.out.println("---------------dtypelen2---" + dtypelen2 + " = " + ns);
//
//                    if (dtypelen2 == ns) {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                //socketUtils.releaseSocket();//接收结束 关闭socket避免 超时操作
//                                Message msg = new Message();
//                                msg.what = MSG_RECEIVE_OVER_DATA;
//                                mHandler.sendMessage(msg);
//                            }
//                        }).start();
//                        onPause();
//                        dtypelen = 0;
//                        return;
//                    } else if (dtypelen2 > ns) {
//                        return;
//                    }
//                    dtypelen0 = dtypelen1;
//                    //System.out.println("---------------dtypelen0---"+dtypelen0);
//                    abmnStr = pyobj1.callAttr("subABMN", abmn, dtype, shape, dtypelen2).toJava(String.class);
//                }
//
//                String[] abmnlis = null;
//                if (abmnStr.length() > 0) {
//                    abmnlis = abmnStr.split(",");
//                }
//                String abmbinx = "";
//                if (boxInx == 0) {
//                    abmbinx = alis.get(0);
//                } else {
//                    abmbinx = alis.get(boxInx);
//                }
//
//                //kSetTxWaveWithParam 3
//                data = pyobj1.callAttr("onSendParamToMcu", "1", send_frequency_value, packet_indx1, send_voltage_value).toJava(byte[].class);
//
//                //SocketMergeUtils.writeMsgByte(data);
//                if (anewSta) {
//                    SocketMergeUtils.writeMsgByte(data);
//                }
//                //kClearAllMuxBoxConnect 15
////                data2 = pyobj1.callAttr("clear_mux", clearStrLisAll[0], clearStrLisAll[1], clearStrLisAll[2], clearStrLisAll[3], clearStrLisAll[4],
////                        clearStrLisAll[5], clearStrLisAll[6], clearStrLisAll[7], clearStrLisAll[8], clearStrLisAll[9]).toJava(byte[].class);
//                if(boxlis.length>0){
//                    data2 = pyobj1.callAttr("clear_mux", boxlis[0], boxlis[1], boxlis[2],boxlis[3], boxlis[4],
//                            boxlis[5], boxlis[6], boxlis[7], boxlis[8], boxlis[9]).toJava(byte[].class);
//                }
//                //kSetMuxBoxConnect 2
//                String box = SwitchBoxUtil.boxIdToSpilt(alis,Integer.parseInt(abmnlis[0]));
//                String box2 = SwitchBoxUtil.boxIdToSpilt(alis,Integer.parseInt(abmnlis[1]));
//                String box3 = SwitchBoxUtil.boxIdToSpilt(alis,Integer.parseInt(abmnlis[2]));
//                String box4 = SwitchBoxUtil.boxIdToSpilt(alis,Integer.parseInt(abmnlis[3]));
//                Arrange arrange = new Arrange();
//                arrange.setItemId(Integer.valueOf(itemsId));
//                List<Arrange> arrangeLis = arrangeService.getArrange(arrange);
//                Integer model = 0;
//                if (arrangeLis.size() > 0) {
//                    model = arrangeLis.get(0).getDeviceType();
//                }
//                System.out.println("++++++++++++++++++++ model ++++++++++++++++++++  ="+model);
//                data3 = pyobj1.callAttr("update_poles_connect", box, box2,
//                        box3, box4,model).toJava(byte[].class);
//                send_piont = "A"+box+"B"+box2;
//                receive_piont = "M"+box3+"N"+box4;
//                send_poiont_val.setText(send_piont);
//                receive_poiont_val.setText(receive_piont);//赋值发射、接收位置
//
//                loding_count = 1;
//
//                try {
//                    if (!startGater) {
//                        Thread.sleep(1);
//                    }
//
//                    if (SocketMergeUtils.success_count < 7) {
//                        onPause();
//                        //System.out.println("===== 挂起=====");
//                    }
//
//                    try {
//                        returnSta = recv_float_array_with_indx(abmnlis);
//                    } catch (IOException e) {
//                        throw new RuntimeException(e);
//                    }
//                    if (returnSta) {
//                        startCount = 0;
//                        inclickGatherCount += 1;
//                        abmn_indx += 1;
//                        SocketMergeUtils.receiveDataAll = "";
//                        SocketMergeUtils.packet_indx = 0;
//                        SocketMergeUtils.packet_lens = 0;
//                        SocketMergeUtils.packet_lens_old = 0;
//                        SocketMergeUtils.success_count = 1;
//                    }
//
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//
//                rec_count_s = 0;
//                //break;
//                //no_id_str = "";
//            }
//        }
//    }
//
//    private void initPython(Context myContext) throws JSONException, InterruptedException {
//        //初始化python环境
//        if (!Python.isStarted()) {
//            Python.start(new AndroidPlatform(myContext));
//        }
//
//        py = Python.getInstance();
//        pyobj = py.getModule("ERT_Plot");
//        //调用hello_python.py里面的plot函式
//        pyobj1 = py.getModule("Send_Param");
//        pyobj2 = py.getModule("fft_ui");
//        pyobjfft = py.getModule("fft_ui");
//    }
//
//    private Boolean getViewInit() {
//        no_data_img = findViewById(R.id.no_data_img);
//        title_back = findViewById(R.id.gather_title_back);
////        stop_gather = findViewById(R.id.stop_gather);
//        start_gather = findViewById(R.id.start_gather);
////        plan_break_char = findViewById(R.id.plan_break_char);
////        arrange_char = findViewById(R.id.arrange_char);
//        img = findViewById(R.id.imageViews);
//
//        plan_break = findViewById(R.id.plan_break);
//        permutations = findViewById(R.id.permutations);
//        waveform = findViewById(R.id.waveform);
//        frequency_spectrum = findViewById(R.id.frequency_spectrum);
//
//        device_type_val = findViewById(R.id.device_type_val);
//        send_frequency_val = findViewById(R.id.send_frequency_val);
//        receive_voltage_val = findViewById(R.id.receive_voltage_val);
//        send_poiont_val = findViewById(R.id.send_poiont_val);
//        receive_poiont_val = findViewById(R.id.receive_poiont_val);
//        filter_type_val = findViewById(R.id.filter_type_val);
//        Sends sends = getSend();
//        if (sends != null) {
//            freq_Indx = freqData[Integer.parseInt(sends.getSendFrequency())];
//            device_type_val.setText(modeData[sends.getType()]);
//            send_frequency_val.setText(freq_Indx + "hz");
//            receive_voltage_val.setText(sends.getVoltage() + "v");
//            repeatUnm = sends.getRepeatNum();
//            filter = Integer.parseInt(sends.getFilterFrequency());
//            filter_type_val.setText(freqFilterData[filter]);
//        } else {
//            Toast.makeText(this, "请先完成发射接收！", Toast.LENGTH_SHORT).show();
//            return false;
//        }
//        return true;
//    }
//
//    private Sends getSend() {
//        sendsService = new SendsService();
//        itemsService = new ItemsService();
//        Items items = new Items();
//        items.setStatus(1);
//        List<Sends> sends = null;
//        try {
//            List<Items> items1 = itemsService.getItems(items);
//            if (items1.size() > 0) {
//                sends = sendsService.getSendsLast(new Sends(items1.get(0).getId()));
//                if (sends.size() > 0) {
//                    return sends.get(0);
//                }
//            } else {
//                Toast.makeText(this, "请先创建项目！", Toast.LENGTH_SHORT).show();
//                return null;
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }
//
//
//    //    private void startStopGather() {
////
////        start_gather.setOnClickListener(new View.OnClickListener() {
////            @Override
////            public void onClick(View v) {
////                start_gather.setText("采集中");
////                sendsService = new SendsService();
////                itemsService = new ItemsService();
////                Items items = new Items();
////                items.setStatus(1);
////                List<Items> items1 = itemsService.getItems(items);
////                List<Sends> sends = sendsService.getSendsLast(new Sends(items1.get(0).getId()));
////
//////                Message msg = new Message();
//////                msg.what = MSG_START;
//////                mHandler.sendMessage(msg);
////
////                Boolean boo = sendMcu(sends.get(0), items1.get(0).getId());
////                if (boo) {
////                    simpleUUID = IdUtil.simpleUUID();
////                    saveSends(sends.get(0));
////                }
////
////
////            }
////        });
////    }
//
//    private void initService() {
//        boxOneService = new BoxOneService();
//        boxTwoService = new BoxTwoService();
//        boxThreeService = new BoxThreeService();
//        boxFourService = new BoxFourService();
//        boxFiveService = new BoxFiveService();
//        boxSixService = new BoxSixService();
//        boxSevenService = new BoxSevenService();
//        boxEightService = new BoxEightService();
//        boxNineService = new BoxNineService();
//        boxTenService = new BoxTenService();
//        Items items = findSelectItem();
//        itemsId = items.getId().toString();
//        //boxLatLon
//        List<String> lisBoxOne = performJoinQuery(itemsId, "tb_boxOne");
//        List<String> lisBoxTwo = performJoinQuery(itemsId, "tb_boxTwo");
//        List<String> lisBoxThree = performJoinQuery(itemsId, "tb_boxThree");
//        List<String> lisBoxFour = performJoinQuery(itemsId, "tb_boxFour");
//        List<String> lisBoxFive = performJoinQuery(itemsId, "tb_boxFive");
//        List<String> lisBoxSix = performJoinQuery(itemsId, "tb_boxSix");
//        List<String> lisBoxSeven = performJoinQuery(itemsId, "tb_boxSeven");
//        List<String> lisBoxEight = performJoinQuery(itemsId, "tb_boxEight");
//        List<String> lisBoxNine = performJoinQuery(itemsId, "tb_boxNine");
//        List<String> lisBoxTen = performJoinQuery(itemsId, "tb_boxTen");
//        if (lisBoxOne.size() > 0) {
//            boxLatLon = new ArrayList<>();
//            String[] str = lisBoxOne.toArray(new String[0]);
//            for (String item : str) {
//                boxLatLon.add(item);
//            }
//        }
//    }
//
//    private List<String> performJoinQuery(String itemId, String tabName) {
//        Items items = findSelectItem();
//        String itemsId = items.getId().toString();
//        SQLiteDatabase db = dbHelper.getReadableDatabase();
//
//        // SQL语句：查询用户表和订单表，根据用户ID关联
//        Cursor cursor = db.rawQuery("select box_one_lat,box_two_lat,box_three_lat,box_four_lat,box_five_lat,box_six_lat,box_seven_lat,box_eight_lat,box_nine_lat,box_ten_lat,box_eleven_lat,box_twelve_lat" +
//                " from " + tabName + " where item_id = ? ", new String[]{itemId});
//        System.out.println(cursor.getCount());
//        List<String> lis = new ArrayList<>();
//        // 遍历结果集
//        while (cursor.moveToNext()) {
//            String box_one_lat = cursor.getString(0);
//            String box_two_lat = cursor.getString(1);
//            String box_three_lat = cursor.getString(2);
//            String box_four_lat = cursor.getString(3);
//            String box_five_lat = cursor.getString(4);
//            String box_six_lat = cursor.getString(5);
//            String box_seven_lat = cursor.getString(6);
//            String box_eight_lat = cursor.getString(7);
//            String box_nine_lat = cursor.getString(8);
//            String box_ten_lat = cursor.getString(9);
//            String box_eleven_lat = cursor.getString(10);
//            String box_twelve_lat = cursor.getString(11);
//            lis.add(box_one_lat);
//            lis.add(box_two_lat);
//            lis.add(box_three_lat);
//            lis.add(box_four_lat);
//            lis.add(box_five_lat);
//            lis.add(box_six_lat);
//            lis.add(box_seven_lat);
//            lis.add(box_eight_lat);
//            lis.add(box_nine_lat);
//            lis.add(box_ten_lat);
//            lis.add(box_eleven_lat);
//            lis.add(box_twelve_lat);
//
//            // 处理查询结果
//            // ...
//        }
//
//        cursor.close();
//        db.close();
//        return lis;
//    }
//
//    public void getTask() {
//        SocketMergeUtils.success_count = 6;
//        byte[] data5 = pyobj1.callAttr("onKReSync", SocketMergeUtils.packet_indx).toJava(byte[].class);
//        SocketMergeUtils.writeMsgByte(data5);
//        System.out.println(" 超时重复开始= " + DateUtils.parseYmdHmsDate());
//    }
//
//    public void saveSends(Sends send) {
//        SocketMergeUtils.success_count = 1;
//        Sends sends = new Sends();
//        sends.setVoltage(send.getVoltage());
//        sends.setType(1);
//        sends.setStatus(0);
//        sends.setUid(simpleUUID);
//        //sends.setElectricity(String.valueOf(send_electric_val.getText()));
//        sends.setRepeatNum(send.getRepeatNum());
//        sends.setSendFrequency(send.getSendFrequency());
//        sends.setSendDuration(send.getSendDuration());
//        sends.setItemId(send.getItemId());
//        sends.setBoxaddr(send.getBoxaddr());
//        sends.setFilterFrequency(send.getFilterFrequency());
//        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        Date date = new Date(System.currentTimeMillis());
//        sends.setCreateTime(sim.format(date));
//        sends.setUpdateTime(sim.format(date));
//        sendsService = new SendsService();
//        boolean bl = sendsService.save(sends);
//        //String simpleUUID = IdUtil.simpleUUID();
//        fileName = FileDownUtil.getFileName(simpleUUID);
//        if (bl) {
//            System.out.println("采集数据保存成功！");
//        }
//        if (inclickGatherCount == 0) {
//            Thread.State state = myThread.getState();
//            System.out.println(state);
////            if(state == Thread.State.WAITING){
////                myThread.
////            }
//            myThread = null;
//            if (null != myThread) {
//
//                try {
//                    myThread.interrupt();
//
//                    Thread.sleep(10);
//                    myThread.start();
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//            myThread = new MyThread();
//            myThread.start();
//
//        } else {
//            inclickGatherCount = 0;
//            myThread.resumeThread();
//            returnSta = true;
////                    SocketMergeUtils.success_count = 0;
//            //SocketMergeUtils.writeMsg("22,M;");
////            SocketMergeUtils.success_count = 0;
////            SocketMergeUtils.writeMsg("22,M;");
//        }
//    }
//
//    public Boolean sendMcu(Sends sends, Integer itemId) {
//
//        send_frequency_value = String.valueOf(Integer.parseInt(sends.getSendFrequency()) + 1);
//        send_repeat_value = sends.getRepeatNum();
//        send_voltage_value = sends.getVoltage();
//        //clearStrLisAll = sends.getBoxaddr().split(",");
//        packet_indx1 = Integer.parseInt(String.valueOf(send_repeat_value));
//        packet_indx = packet_indx1;
//        sf = Integer.parseInt(sends.getSendFrequency());
//        int send_repeat = Integer.parseInt(send_repeat_value);
//        repate_indx = new int[send_repeat];
//        for (int i = 0; i < send_repeat; i++) {
//            repate_indx[i] = i;
//        }
//        Arrange arrange1 = new Arrange();
//        arrange1.setItemId(itemId);
//        List<Arrange> arrangeLis = arrangeService.getArrange(arrange1);
//        //Integer ns = 0;
//
//        if (arrangeLis.size() == 0) {
//            Toast.makeText(this, "请先添加排列设计！", Toast.LENGTH_SHORT).show();
//            return false;
//        } else {
//            //ns = arrangeLis.get(0).getDeviceTypeLen();
//            dtype = arrangeLis.get(0).getDtype();
//            dtypelen = arrangeLis.get(0).getDeviceTypeLen();
//            shape = arrangeLis.get(0).getShape();
//            abmn = arrangeLis.get(0).getDeviceTypeVal();
//            Integer devtype = arrangeLis.get(0).getDeviceType();
//            permutationMode = modeData[devtype];//添加采集模式
//            dtypelen0 = dtypelen;
//        }
//        // myThread.start();
//        return true;
//    }
//
//    private synchronized Boolean recv_float_array_with_indx(String[] abmnlis) throws InterruptedException, IOException {
////        Timer timer = new Timer();
////        TimerTask task = new TimerTask() {
////            @Override
////            public void run() {
////                SocketUtils.success_count = 6;
////                byte[] data4 = pyobj1.callAttr("onKConfirmToMcu", SocketUtils.packet_indx).toJava(byte[].class);
////                SocketUtils.writeMsgByte(data4);
////                System.out.println(" 超时重复开始= " + DateUtils.parseYmdHmsDate());
////            }
////        };
//        int status = 0;
//        int error = 0;
//        int rec_count = 0;
//        int bak_packet_lens = 0;
//        int bak_indx = 0;
//        int re_indx = 0;
//        returnSta = false;
//        recv_float_bool = true;
//        Double[] cv_lis = null;
//        jbA = new JSONArray();
//        //jb = new JSONObject();
//        JSONObject jb = null;
//        tx_c_rx_v_lis = new ArrayList<Double[]>();
//        // Map<String, ArrayList<Double[]>> data_map = new HashMap<String, ArrayList<Double[]>>();
//        Boolean headSta = false;
//        Boolean indxSta = false;
//        Boolean txvSta = false;
//        Boolean txcSta = false;
//        Boolean rxvSta = false;
//
//        while (recv_float_bool) {
//            cv_lis = new Double[2];
//            //if (queue != null) {
//            //Log.i("buffer","-------------success_count = "+SocketUtils.success_count );
//            if (socketUtils.success8) {
//                if (SocketMergeUtils.success_count > 7) {
//                    bak_packet_lens = SocketMergeUtils.packet_lens_old / 3;
//                    error = 0;
//                    if (!errorSta) {
//                        //接收包头AA55
//                        receive_one_field_sta = true;
//                        Map<String, Object> map = receive_one_field1("AA55");
//                        receive_one_field_sta = false;
//                        List<Byte> ab = dataParseUtil.objToByList(map.get("one_field"));
//
//                        byte[] str_one_field = dataParseUtil.listTobytes(ab);
//                        int str_one_field_len = str_one_field.length;
//                        Boolean timeout = (Boolean) map.get("timeout");
//
//                        if (timeout) {
//                            error = error + 1;
//                            //break;
//                        }
//
//                        if (str_one_field_len > 0) {
//
//                            if (str_one_field[0] == 0) {
//                                System.out.println("header len error 0" + str_one_field + " --- " + Arrays.toString(str_one_field));
//                                //continue;
//                                error += 1;
//                                boolErr = true;
//                                indxSta = true;
//                                txvSta = true;
//                                txcSta = true;
//                                //continue;
//                            } else if (str_one_field_len < 2) {
//                                System.out.println("header len error 1" + str_one_field + " --- " + Arrays.toString(str_one_field));
//                                //System.out.println("last indx= " + bak_indx);
//                                //continue;
//                                error += 1;
//                                boolErr = true;
//                                indxSta = true;
//                                txvSta = true;
//                                txcSta = true;
//                                //continue;
//                            } else if (str_one_field_len > 2) {
//                                error = error + 1;
//                                boolErr = true;
//                                indxSta = true;
//                                txvSta = true;
//                                txcSta = true;
//                                System.out.println("header len >4, break: " + str_one_field + " --- " + Arrays.toString(str_one_field));
//                                break;
//                            } else {
//                                int header = recv_unsigned_int(str_one_field);
//
//                                //                         vol_ele += ContextVariable.freq + ",";
//                                //vol_ele += packet_indx + ",";
//                                queueMsg.enQueue(ContextVariable.freq + ", ");
//                                queueMsg.enQueue(SocketMergeUtils.packet_indx + ", ");
//                                //System.out.println("00000000000000000000 header= " + header);
//                                if (header != 0xAA55) {
//                                    System.out.println("header error " + new String(str_one_field));
//                                    boolErr = true;
//                                    indxSta = true;
//                                    txvSta = true;
//                                    txcSta = true;
//                                }
//                            }
//                        }
//                    }
//
//                    //接收包的indx
//                    //需要对接收到的_receive_one_field的长度做判断，如果长度不够，就认为接收出错
//                    int indx = 0;
//                    if (!headSta) {
//                        receive_one_field_sta = true;
//                        Map<String, Object> map2 = receive_one_field1("indx");
//                        receive_one_field_sta = false;
//                        List<Byte> ab2 = dataParseUtil.objToByList(map2.get("one_field"));
//                        byte[] str_one_field2 = dataParseUtil.listTobytes(ab2);
//                        int str_one_field2_len = str_one_field2.length;
//                        Boolean timeout2 = (Boolean) map2.get("timeout");
//                        //System.out.println("--------------------str_one_field2--------------------" + str_one_field2);
//                        if (timeout2) {
//                            error = error + 1;
//                            boolErr = true;
//                            indxSta = true;
//                            txvSta = true;
//                            txcSta = true;
//                            //break;
////                        }
//                        }
//                        if (str_one_field2_len > 0) {
//                            //int str_lens = dataParseUtil.entiretyDecodeStructByteBack(str_one_field2);
//                            if (str_one_field2_len != 2) {
//                                error = error + 1;
//                                //errorCount = false;
//                                boolErr = true;
//                                indxSta = true;
//                                txvSta = true;
//                                txcSta = true;
//                                //break;
//                            } else {
//                                indx = recv_unsigned_int(str_one_field2);
//                                if (indx == 43605) {
//                                    //System.out.println("接收包的indx 出错  " + indx);
//                                }
//                                if (errorSta) {
//                                    //System.out.println("接收包的indx 出错  " + indx);
//                                } else {
//                                    //System.out.println("接收包的indx正常-----------  " + indx);
//                                }
//                                errorSta = false;
//
//
//                                queueMsg.enQueue(indx + ", ");
//                                queueMsg.enQueue(abmnlis[0] + ", ");
//                                queueMsg.enQueue(abmnlis[1] + ", ");
//                                queueMsg.enQueue(abmnlis[2] + ", ");
//                                queueMsg.enQueue(abmnlis[3] + ", ");
////                        /System.out.println("  ============abmn======== "+abmnlis[0]+","+abmnlis[1]+","+abmnlis[2]+","+abmnlis[3]);
//                                //System.out.println("-------str_one_field2--indx--- " + indx);
//
//                                if (indx > bak_packet_lens) {
//                                    error = error + 1;
//                                    //errorCount = false;
//                                    boolErr = true;
//                                    indxSta = true;
//                                    txvSta = true;
//                                    txcSta = true;
//                                    //break;
//                                }
//                            }
//                        }
//                    }
//
//                    //tx_voltage_data
//                    if (!indxSta) {
//                        receive_one_field_sta = true;
//                        Map<String, Object> map3 = receive_one_field1("tx_voltage_data");
//                        receive_one_field_sta = false;
//                        List<Byte> ab3 = dataParseUtil.objToByList(map3.get("one_field"));
//                        byte[] str_one_field3 = dataParseUtil.listTobytes(ab3);
//                        int str_one_field3_len = str_one_field3.length;
//                        Boolean timeout3 = (Boolean) map3.get("timeout");
//                        //System.out.println("--------------------str_one_field3--------------------" + str_one_field3);
//                        if (timeout3) {
//                            error = error + 1;
//                            //errorCount = false;
//                            boolErr = true;
//                            indxSta = true;
//                            txvSta = true;
//                            txcSta = true;
//                            //break;
//                        }
//                        String tx_voltage1 = null;
//                        if (str_one_field3_len > 0) {
//                            //int str_lens = dataParseUtil.entiretyDecodeStructByteBack(str_one_field3);
//                            if (str_one_field3_len != 4) {
//                                error = error + 1;
//                                boolErr = true;
//                                indxSta = true;
//                                txvSta = true;
//                                txcSta = true;
//                                //break;
//                            } else {
//                                tx_voltage1 = recv_float(str_one_field3);
//
//                                //System.out.println("--------------------tx_voltage1--------------------" + tx_voltage1);
//                                // vol_ele += tx_voltage1 + ",";
//                                queueMsg.enQueue(tx_voltage1 + ", ");
//                            }
//                        }
//                    }
//
//                    //tx_current_data
//                    int tx_current1_len = 0;
//                    String tx_current1 = null;
//                    if (!txvSta) {
//                        receive_one_field_sta = true;
//                        Map<String, Object> map4 = receive_one_field1("tx_current_data");
//                        receive_one_field_sta = false;
//                        List<Byte> ab4 = dataParseUtil.objToByList(map4.get("one_field"));
//                        byte[] str_one_field4 = dataParseUtil.listTobytes(ab4);
//                        int str_one_field4_len = str_one_field4.length;
//                        Boolean timeout4 = (Boolean) map4.get("timeout");
//                        //System.out.println("--------------------str_one_field4--------------------" + str_one_field4);
//                        if (timeout4) {
//                            error = error + 1;
//                            boolErr = true;
//                            indxSta = true;
//                            txvSta = true;
//                            txcSta = true;
//                            //break;
//                        }
//                        if (str_one_field4_len > 0) {
//                            tx_current1_len = str_one_field4_len;
//                            //int str_lens = dataParseUtil.entiretyDecodeStructByteBack(str_one_field4);
//                            if (str_one_field4_len != 4) {
//                                error = error + 1;
//                                // break;
//                                boolErr = true;
//                                indxSta = true;
//                                txvSta = true;
//                                txcSta = true;
//                            } else {
//                                tx_current1 = recv_float(str_one_field4);
//                                cv_lis[0] = Double.valueOf(tx_current1);
//                                queueMsg.enQueue(tx_current1 + ", ");
//                            }
//                        }
//                    }
//
//                    //rx_voltage_data
//                    int rx_voltage1_len = 0;
//                    String rx_voltage1 = null;
//                    if (!txcSta) {
//                        int indx_end = 0;
//                        receive_one_field_sta = true;
//
//                        Map<String, Object> map5 = receive_one_field1("rx_voltage_data");
//                        //System.out.println(indx);
//                        receive_one_field_sta = false;
//                        List<Byte> ab5 = dataParseUtil.objToByList(map5.get("one_field"));
//                        //byte[] str_one_field5 = dataParseUtil.listTobyte(ab5);
//                        byte[] str_one_field5 = dataParseUtil.listTobytes(ab5);
//                        int str_one_field5_len = str_one_field5.length;
//                        Boolean timeout5 = (Boolean) map5.get("timeout");
//                        // System.out.println("--------------------str_one_field5--------------------" + str_one_field5);
//
//                        if (timeout5) {
//                            error = error + 1;
//                            //break;
//                            boolErr = true;
//                            indxSta = true;
//                            txvSta = true;
//                            txcSta = true;
//
//                        }
//                        if (str_one_field5_len > 0) {
//                            rx_voltage1_len = str_one_field5_len;
//                            //int str_lens = dataParseUtil.entiretyDecodeStructByteBack(str_one_field5);
//                            if (str_one_field5_len != 4) {
//                                error = error + 1;
//                                //break;
//                                boolErr = true;
//                                rxvSta = true;
//                            } else {
//                                rx_voltage1 = recv_float(str_one_field5);
//                                cv_lis[1] = Double.valueOf(rx_voltage1);
//
//                                queueMsg.enQueue(rx_voltage1 + ", ");
//
//                            }
//                        }
//                    }
//                    if (!"".equals(rx_voltage1) && !"".equals(tx_current1)) {//极化率
//                        if (rx_voltage1_len == 4 && tx_current1_len == 4) {//过滤到出错的数据
//                            String polarizability = pyobjfft.callAttr("polarizability", rx_voltage1, tx_current1).toJava(String.class);
//                            queueMsg.enQueue(polarizability+", ");
//                            queueMsg.enQueue(permutationMode+ ";");
//                        }
//
//                    }
//                    if (error == 0) {
//                        rec_count = rec_count + 1;
//
//
//                        //rx_voltage_data += rx_voltage1 + ",";
//                        rx_voltage_data1.append(rx_voltage1 + ",");
//                        SocketMergeUtils.packet_lens -= 3;
//                        tx_c_rx_v_lis.add(cv_lis);
//                        if (SocketMergeUtils.packet_lens <= 0) {
//
//                            if (bak_packet_lens == rec_count) {
//
//                                try {
//                                    ArrayList<Double[]> tx_c_rx_v_lis_all = new ArrayList<>();
//                                    tx_c_rx_v_lis_all.addAll(tx_c_rx_v_lis);
//                                    jb = new JSONObject();
//                                    //直接在 list对象填充到json对象之前定义这行就行了 没作用
//                                    //JSON.toJSONString(tx_c_rx_v_lis, SerializerFeature.DisableCircularReferenceDetect);
//                                    jb.put(String.valueOf(repate_indx[re_indx]), tx_c_rx_v_lis_all);
//                                    if (Integer.parseInt(repeatUnm) > 1) {
//                                        re_indx += 1;
//                                    }
//
//                                    jb_tu.putAll(jb);
//                                    tx_c_rx_v_lis.clear();
//
//                                } catch (JSONException e) {
//                                    throw new RuntimeException(e);
//                                }
//                                System.out.println(" =============== 4,start; 结束= " + DateUtils.parseYmdHmsDate());
//                                //System.out.println(rx_voltage_data);
//                                recv_float_bool = false;
//                                receive_one_field_sta = false;
//
//                                SocketMergeUtils.resumeThread();
//                                SocketMergeUtils.success_count = 6;
//
//                                anewSta = true;
//                                byte[] data4 = pyobj1.callAttr("onKConfirmToMcu", rec_count).toJava(byte[].class);
//                                SocketMergeUtils.writeMsgByte(data4);
//
//                                System.out.println(" 重复开始1= " + DateUtils.parseYmdHmsDate());
//
//                                recv_float_bool = true;
//                                receive_one_field_sta = true;
//
//                                //System.out.println(" 点击结束= " + DateUtils.parseYmdHmsDate());
//                                SocketMergeUtils.packet_indx -= 1;
//                                rec_count_s = rec_count;
//                                rec_count = 0;
//                                back_over = true;
//                                receive_packet_indx_count += 1;
//                                // rx_voltage_data_all += rx_voltage_data + ";";
//                                rx_voltage_data_all1.append(rx_voltage_data1.toString() + ";");
//
//                                new Thread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        saveCvs();
//                                    }
//                                }).start();
//
//                                if (SocketMergeUtils.packet_indx == 0) {
//                                    re_indx = 0;
//                                    String[] rxStrList = rx_voltage_data_all1.toString().split(";");
//                                    String rx_voltage_data_add = ArrayUtil.strToStrArrrayAdd(rxStrList);
//                                    rx_voltage_data_len = rx_voltage_data_add.substring(0, rx_voltage_data_add.length() - 1).split(",").length;
//
//                                    if (!rx_voltage_data_add.equals("")) {
//                                        //jb_tu.putAll(jb);
//                                        jb_tu_str = jb_tu.toString();
//                                        jsonObjectMsg = initJson();
//                                        if (gatherType == 1) {
//                                            Message msg = new Message();
//                                            msg.what = MSG_RECEIVE_TU_DATA;
//                                            msg.arg1 = dtypelenAbmn;
//                                            msg.obj = rx_voltage_data_add;
//                                            mHandler.sendMessage(msg);
//                                        } else if (gatherType == 2) {
//                                            Message msg = new Message();
//                                            msg.what = MSG_RECEIVE_PAI_DATA;
//                                            msg.arg1 = dtypelenAbmn;
//                                            msg.obj = rx_voltage_data_add;
//                                            mHandler.sendMessage(msg);
//                                        } else if (gatherType == 3) {
//                                            Message msg = new Message();
//                                            msg.what = MSG_RECEIVE_BO_DATA;
//                                            msg.arg1 = dtypelenAbmn;
//                                            msg.obj = rx_voltage_data_add;
//                                            mHandler.sendMessage(msg);
//                                        } else if (gatherType == 4) {
//                                            Message msg = new Message();
//                                            msg.what = MSG_RECEIVE_PIN_DATA;
//                                            msg.arg1 = dtypelenAbmn;
//                                            msg.obj = rx_voltage_data_add;
//                                            mHandler.sendMessage(msg);
//                                        }
//
//                                        cv_lis = null;
//                                    }
//
////                            rx_voltage_data_all = "";
////                            rx_voltage_data = "";
//                                    rx_voltage_data1 = new StringBuffer();
//                                    rx_voltage_data_all1 = new StringBuffer();
//                                    returnSta = true;
//                                    Thread.sleep(1000);
//                                    break;
//                                }
//                                //返回正确确认包，
//                                status = 0;
//
//                            } else {
////                        byte[] data4 = pyobj1.callAttr("onKConfirmToMcu", 0).toJava(byte[].class);
////                        SocketUtils.writeMsgByte(data4);
//                                status = 1;
//                            }
//                        }
//                    } else if (SocketMergeUtils.packet_lens > 0 && indx == 1) {//数据丢包处理，index =1 重新发送命令
//                        Thread.sleep(1000);
//                        System.out.println("------------ bytecount error ==============" + socketUtils.bytecount + "--" + SocketMergeUtils.packet_lens + "--" + indx);
//                        socketUtils.bytecount = 0;
//                        rx_voltage_data1 = new StringBuffer();
//                        tx_current_data1 = new StringBuffer();
//                        rx_voltage_data_all1 = new StringBuffer();
//                        errorSta = false;
//                        errorCount = false;
//                        anewSta = false;
//                        error = 0;
//                        returnSta = false;
//                        rec_count = 0;
//                        SocketMergeUtils.resumeThread();
//                        SocketMergeUtils.success_count = 5;
//
//                        SocketMergeUtils.packet_lens = SocketMergeUtils.packet_lens_old;
//                        //SocketMergeUtils.packet_lens=0;
//                        queueMsg.clear();
//                        Thread.sleep(10);
//                        byte[] data4 = pyobj1.callAttr("onKReSync", SocketMergeUtils.packet_indx).toJava(byte[].class);
//                        SocketMergeUtils.writeMsgByte(data4);
//                        System.out.println(" 数据丢包，重复开始= " + DateUtils.parseYmdHmsDate());
//
//                    } else {
//                        Boolean bl1 = false;
//                        Boolean bl2 = false;
//                        while (boolErr) {
//                            receive_one_field_sta = false;
////                            int tmp = socketUtils.read21();
////                            if (tmp == -1) {
////                                errorSta = false;
////                                rec_count = 0;
////                                SocketMergeUtils.packet_lens = 0;
////                                boolErr = false;
////                                bl2 = false;
////                                receive_one_field_sta = true;
////                                headSta = false;
////                                indxSta = false;
////                                txvSta = false;
////                                txcSta = false;
////                                rxvSta = false;
////                                error = 0;
////                                rx_voltage_data1 = new StringBuffer();
////                                tx_current_data1 = new StringBuffer();
////                                rx_voltage_data_all1 = new StringBuffer();
////                                returnSta = true;
////                                SocketMergeUtils.resumeThread();
////                                SocketMergeUtils.success_count = 5;
////                                recv_float_bool = false;
////                                byte[] data4 = pyobj1.callAttr("onKReSync", SocketMergeUtils.packet_indx).toJava(byte[].class);
////                                SocketMergeUtils.writeMsgByte(data4);
////                                System.out.println(" 数据出错，重复开始= " + DateUtils.parseYmdHmsDate());
////                            }
//                            byte tmp = socketUtils.read();
//
//                            //System.out.println("tmp ===" + Arrays.toString(tmp));
//                            //System.out.println("================bytecount ===" + SocketMergeUtils.bytecount);
//                            Thread.sleep(1000);
//                            if (String.valueOf(tmp).equals("85")) {
//                                //System.out.println("tmp ===" + tmp);
//                                bl1 = true;
//                                continue;
//                            }
//                            if (bl1) {
//                                if (String.valueOf(tmp).equals("-86")) {
//                                    //System.out.println("tmp2 ===" + tmp);
//                                    bl2 = true;
//                                    bl1 = false;
//                                    continue;
//                                }
//                            }
//                            if (bl2) {
//                                System.out.println("tmp3 ===" + tmp);
//                                errorSta = true;
//                                rec_count = rec_count + 1;
//                                SocketMergeUtils.packet_lens -= 3;
//                                boolErr = false;
//                                bl2 = false;
//                                receive_one_field_sta = true;
//                                headSta = false;
//                                indxSta = false;
//                                txvSta = false;
//                                txcSta = false;
//                                rxvSta = false;
//                                error =0;
//                                break;
//
//                            }
//
//                        }
//                        System.out.println("tmp333333333333333333333333333333333333333 ===");
//
//                        continue;
//                    }
//                }
//                //}
//            }
//        }
//        return returnSta;
//    }
//
//    public Boolean errorHandle() {
//        SocketMergeUtils.success_count = 8;
//        errorCount = false;
//        anewSta = false;
//        System.out.println("=================error > 0================");
//        bool = false;
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        SocketMergeUtils.success_count = 8;
//        SocketMergeUtils.resumeThread();
//
//        returnSta = false;
//        Boolean bool1 = true;
//
//        while (bool1) {
//            if (!socketUtils.success8) {
//                //byte[] data5 = pyobj1.callAttr("onKReSync", SocketMergeUtils.packet_indx).toJava(byte[].class);
//                //SocketMergeUtils.writeMsgByte(data5);
//                System.out.println("---------------------错误结束-----------------");
//                bool1 = false;
//                socketUtils.success8 = true;
//                Timer timer = new Timer();
//                TimerTask task = new TimerTask() {
//                    @Override
//                    public void run() {
//                        getTask();
//                    }
//                };
//                timer.schedule(task, 0, timeouts);
//                timer.cancel();
//                break;
//            }
//        }
//        return bool1;
//    }
////    public Boolean errorHandle() {
////        SocketMergeUtils.releaseSocket();
////        startGater = false;
////        msg_sueecss_count = 0;
////        //SocketMergeUtils.success_count = 5;
////        socketUtils = SocketMergeUtils.getInstance();
////        if (SocketMergeUtils.socket == null) {
////            Toast toast = Toast.makeText(myContext, "网络连接失败！", Toast.LENGTH_SHORT);
////            toast.setGravity(Gravity.CENTER, 0, 0);
////            toast.show();
////            GatherDataActivity.this.finish();
////        }else {
////            getTask();
////        }
////        return false;
////    }
//
//    private synchronized Map<String, Object> receive_one_field1(String name) throws InterruptedException {
//        Map<String, Object> map = new HashMap<>();
//        Boolean escaped = false;
//        Boolean command_sep_found = false;
//        ArrayList<Byte> one_field = new ArrayList<Byte>();
//        Boolean timeout = false;
//
//        while (receive_one_field_sta) {
//            byte tmp = socketUtils.read();
//            //System.out.println("9999999999999999999999------- tmp=" + tmp);
////            if(tmp == 0){
////                continue;
////            }
//            //System.out.println("9999999999999999999999------- tmp=" + tmp);
//            // System.out.println("9999999999999999999999------- name=" + name);
//            //System.out.println("queue 不是空 = " + queue.QueueEmpty()+" ----  mTheead ="+mReceiveThread.getState());
//
//            if (escaped) {
//                if (tmp == 44 || tmp == 59 || tmp == 47) {
//                    one_field.add(tmp);
//                    escaped = false;
//                } else {
//                    one_field.add(tmp);
//                    escaped = false;
//                }
//            } else {
//                if (tmp == 47) {
//                    //遇到 / 就escaped = True 继续循环
//                    escaped = true;
//                } else if (tmp == 44) {
//                    break;
//                } else if (tmp == 59) {
//                    command_sep_found = true;
//                    break;
//                } else {
//                    one_field.add(tmp);
//                }
//            }
//            //tmp = Byte.parseByte(null);
//        }
//        map.put("one_field", one_field);
//        map.put("timeout", timeout);
//
//        return map;
//    }
//
//    private Map<String, Object> receive_one_field(String name) throws InterruptedException {
//        Map<String, Object> map = new HashMap<>();
//        Boolean escaped = false;
//        Boolean command_sep_found = false;
//        ArrayList<Byte> one_field = new ArrayList<Byte>();
//        Boolean timeout = false;
//
//        while (receive_one_field_sta) {
//            Thread.sleep(0);
//            if (queue.QueueEmpty()) {
//                //System.out.println("queue 是空队列 = " + queue.QueueEmpty()+" ----  mTheead ="+mReceiveThread.getState());
//            } else {
//                //System.out.println("9999999999999999999999------- queue=" + queue.QueueEmpty());
//                if (queue.QueueLength() > 0) {
//
//                    byte tmp = (byte) queue.deQueue();
//                    //System.out.println("9999999999999999999999------- tmp=" + tmp);
//                    // System.out.println("9999999999999999999999------- name=" + name);
//                    //System.out.println("queue 不是空 = " + queue.QueueEmpty()+" ----  mTheead ="+mReceiveThread.getState());
//
//
//                    if (escaped) {
//                        if (tmp == 44 || tmp == 59 || tmp == 47) {
//                            one_field.add(tmp);
//                            escaped = false;
//                        } else {
//                            one_field.add(tmp);
//                            escaped = false;
//                        }
//                    } else {
//                        if (tmp == 47) {
//                            //遇到 / 就escaped = True 继续循环
//                            escaped = true;
//                        } else if (tmp == 44) {
//                            break;
//                        } else if (tmp == 59) {
//                            command_sep_found = true;
//                            break;
//                        } else {
//                            one_field.add(tmp);
//                        }
//                    }
//                }
//            }
//        }
//        map.put("one_field", one_field);
//        map.put("timeout", timeout);
//        // System.out.println(one_field);
//        return map;
//    }
//
//    private Integer recv_unsigned_int(byte[] val) {
//
//        return dataParseUtil.recv_unsigned_int(val);
//    }
//
//    private String recv_float(byte[] val) {
//        return dataParseUtil.recv_float(val);
//    }
//
//
//    public void displayChart() {
//        mChart1.setVisibility(View.GONE);
//        mChart2.setVisibility(View.GONE);
//        mChart3.setVisibility(View.GONE);
//        mChart4.setVisibility(View.GONE);
//    }
//
//    public void onClick(View v) {
//        displayChart();
//        switch (v.getId()) {
//            case R.id.plan_break:
//                gatherType = 1;
//                planBreak();
//                break;
//            case R.id.permutations:
//                gatherType = 2;
//                permutations();
//                break;
//            case R.id.waveform:
//                gatherType = 3;
//                waveform();
//                break;
//            case R.id.frequency_spectrum:
//                gatherType = 4;
//                frequencySpectrum();
//                break;
//            default:
//                break;
//        }
//
//    }
//
//    private void planBreak() {
//        no_data_img.setVisibility(View.GONE);
//
//        img.setVisibility(View.VISIBLE);
//        mChart1.setVisibility(View.VISIBLE);
//        mChart2.setVisibility(View.GONE);
//        mChart3.setVisibility(View.GONE);
//        mChart4.setVisibility(View.GONE);
//        plan_break.setTextColor(Color.parseColor("#FF007AFF"));
//        permutations.setTextColor(Color.parseColor("#A6000000"));
//        waveform.setTextColor(Color.parseColor("#A6000000"));
//        frequency_spectrum.setTextColor(Color.parseColor("#A6000000"));
//        plan_break.setTextSize(18);
//        permutations.setTextSize(16);
//        waveform.setTextSize(16);
//        waveform.setTextSize(16);
//
////        plan_break_char.setVisibility(View.VISIBLE);
////        arrange_char.setVisibility(View.GONE);
//
////        JSONObject jsonObject = new JSONObject();
////        Items items = null;
////        Arrange arrange = new Arrange();
////        try {
////            items = findSelectItem();
////            if (null != items) {
////                arrange.setItemId(items.getId());
////                Arrange arrange1 = new Arrange();
////                arrange1.setItemId(items.getId());
////                List<Arrange> arrangeLis = arrangeService.getArrange(arrange1);
////                Arrange arrange2 = arrangeLis.get(0);
////                jsonObject.put("data", jb_tu);
////                jsonObject.put("num_electrodes", "20");
////                jsonObject.put("Max_n_spacing", "20");
////                jsonObject.put("Aspacing", "10");
////                jsonObject.put("ChnNO", "10");
////                jsonObject.put("ABMN", arrange2.getDeviceTypeVal());
////                jsonObject.put("TXFrq", "8");
////                jsonObject.put("TXDuty", "10");
////                jsonObject.put("CycleNO", "10");
////                jsonObject.put("StackNO", send_repeat_value);
////                jsonObject.put("RXSR", SocketMergeUtils.packet_lens/3);
////                jsonObject.put("dtype", arrange2.getDtype());
////                jsonObject.put("shape", arrange2.getShape());
////                jsonObject.put("path", "/data/data/com.example.shiwu/files/1-9f0a4c7f39674bb68e1b20b0505044c3.cvs");
////
////                int ns = dataParseUtil.ERTuiSectionNs(jsonObject.toString());
////
////
////                new Thread() {
////                    @Override
////                    public void run() {
////                        for (int i = 0; i < ns; i++) {
////                            runOnUiThread(new Runnable() {
////                                public void run() {
////                                    displayChart();
////                                }
////                            });
////
////
////                            if(gatherType !=1){
////                                try {
////                                    this.join();
////                                } catch (InterruptedException e) {
////                                    throw new RuntimeException(e);
////                                }
////                            }else if (gatherType == 1) {
////                                runOnUiThread(new Runnable() {
////                                    public void run() {
////                                        mChart1.setVisibility(View.VISIBLE);
////                                    }
////                                });
////
////                            }
////                            byt = dataParseUtil.AnalyzeJonsJson(jb_tu.toString(), jsonObject.toString(), String.valueOf(i),ns);
////                            Message msg = new Message();
////                            msg.what = MSG_RECEIVE_SECTION_DATA;
////                            msg.obj = byt;
////                            mHandler.sendMessage(msg);
////                        }
////                    }
////                }.start();
//
//
////            }
////        } catch (JSONException e) {
////            throw new RuntimeException(e);
////        }
//
//    }
//
//    private Items findSelectItem() {
//        itemsService = new ItemsService();
//        Items items = new Items();
//        items.setStatus(1);
//        List<Items> lis = itemsService.getItems(items);
//        if (lis.size() > 0) {
//            return lis.get(0);
//        }
//        return null;
//    }
//
//    private void permutations() {
//        img.setVisibility(View.VISIBLE);
//        no_data_img.setVisibility(View.GONE);
//        mChart2.setVisibility(View.VISIBLE);
//        mChart1.setVisibility(View.GONE);
//        mChart3.setVisibility(View.GONE);
//        mChart4.setVisibility(View.GONE);
//        plan_break.setTextColor(Color.parseColor("#A6000000"));
//        permutations.setTextColor(Color.parseColor("#FF007AFF"));
//        waveform.setTextColor(Color.parseColor("#A6000000"));
//        frequency_spectrum.setTextColor(Color.parseColor("#A6000000"));
//
//        plan_break.setTextSize(16);
//        permutations.setTextSize(18);
//        waveform.setTextSize(16);
//        waveform.setTextSize(16);
////        plan_break_char.setVisibility(View.GONE);
////        arrange_char.setVisibility(View.VISIBLE);
////        img.setVisibility(View.GONE);
//
//    }
//
//    private void waveform() {
//        img.setVisibility(View.VISIBLE);
//        no_data_img.setVisibility(View.GONE);
//        mChart3.setVisibility(View.VISIBLE);
//        mChart1.setVisibility(View.GONE);
//        mChart2.setVisibility(View.GONE);
//
//        mChart4.setVisibility(View.GONE);
//        plan_break.setTextColor(Color.parseColor("#A6000000"));
//        permutations.setTextColor(Color.parseColor("#A6000000"));
//        waveform.setTextColor(Color.parseColor("#FF007AFF"));
//        frequency_spectrum.setTextColor(Color.parseColor("#A6000000"));
//        plan_break.setTextSize(16);
//        permutations.setTextSize(16);
//        waveform.setTextSize(18);
//        frequency_spectrum.setTextSize(16);
//
//    }
//
//    private void frequencySpectrum() {
//        mChart4.setVisibility(View.VISIBLE);
//        no_data_img.setVisibility(View.GONE);
//        img.setVisibility(View.VISIBLE);
//        mChart1.setVisibility(View.GONE);
//        mChart2.setVisibility(View.GONE);
//        mChart3.setVisibility(View.GONE);
//
//        plan_break.setTextColor(Color.parseColor("#A6000000"));
//        permutations.setTextColor(Color.parseColor("#A6000000"));
//        waveform.setTextColor(Color.parseColor("#A6000000"));
//        frequency_spectrum.setTextColor(Color.parseColor("#FF007AFF"));
//        plan_break.setTextSize(16);
//        permutations.setTextSize(16);
//        waveform.setTextSize(16);
//        frequency_spectrum.setTextSize(18);
//
//    }
//
//    private void savebitmap(Bitmap bitmap, String name) {
//
//        //创建文件，因为不存在2级目录，所以不用判断exist，要保存png，这里后缀就是png，要保存jpg，后缀就用jpg
//        File file = new File(ContextVariable.DOWN_NAME + "/img/" + fileName + "_" + name + ".png");
//        File downloadFile = new File(ContextVariable.IMG_DOWN_NAME);
//        try {
//            if (!downloadFile.exists()) {
//                downloadFile.mkdir();
//            }
//            //文件输出流
//            FileOutputStream fileOutputStream = new FileOutputStream(file);
//            //压缩图片，如果要保存png，就用Bitmap.CompressFormat.PNG，要保存jpg就用Bitmap.CompressFormat.JPEG,质量是100%，表示不压缩
//            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
//            //写入，这里会卡顿，因为图片较大
//            fileOutputStream.flush();
//            //记得要关闭写入流
//            fileOutputStream.close();
//            //成功的提示，写入成功后，请在对应目录中找保存的图片
//            //System.out.println("写入成功！目录" + Environment.getExternalStorageDirectory() + "/" + name + ".png");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            //失败的提示
//            System.out.println("写入失败！目录" + Environment.getExternalStorageDirectory() + "/" + name + ".png");
//        } catch (IOException e) {
//            e.printStackTrace();
//            //失败的提示
//            System.out.println("写入失败！目录" + Environment.getExternalStorageDirectory() + "/" + name + ".png");
//        }
//
//    }
//
//    public synchronized void saveCvs() {
//        int len = queueMsg.QueueLength() / 12;
//        String[] vel = new String[len];
//        String[] velLisnew = new String[len];
//        //int ii = 0;
//        for (int i = 0; i < len; i++) {
//            //ii+=1;
//            StringBuffer val = new StringBuffer();
//            for (int j = 0; j < 12; j++) {
//                val.append(queueMsg.deQueue().toString());
//            }
//            //vel[i] = val.toString().replace(";", "");
//            vel[i] = val.toString().replace(";", "\n");
////            String[] velLis = vel[i].toString().split(",");
////            for (int j = 0; j < velLis.length; j++) {
////                if(j==3 || j==4 || j==5 || j==6){
////                    velLis[j] = boxLatLon.get(Integer.parseInt(velLis[j]) - 1);
////                }
////            }
////            String velStr = String.join(",", velLis);
////            velLisnew[i] = velStr+"\n";
//        }
//
//        Integer cvs_line_count = FileDownUtil.saveFileNew(myContext, vel, fileName + ".cvs", cvs_line);
//        cvs_line = cvs_line_count;
//
//        //String[] vel =queueMsg.toArray();
//        //String[] vel = vol_ele.split(";");
//        //生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
////        String simpleUUID = IdUtil.simpleUUID();
////        String fileName = FileDownUtil.getFileName(simpleUUID);
//        //FileDownUtil.saveFile(myContext, vel, simpleUUID);
//
////        List<ReceiveVolEle> lis = new ArrayList<ReceiveVolEle>();
////        ReceiveVolEle rve = null;
////        MyQueue queue1 = new MyQueue();
////        int ii = 0;
////        if (!receive_sta) {
////            ii = 1;
////        }
////        for (int i = ii; i < vel.length; i++) {
////            String vel_new = "";
//////                        if (i != 0) {
//////                            vel_new = vel[i].substring(1, vel[i].length());
//////                        } else {
////
////
////            vel_new = vel[i];
////            //}
////            if (!vel_new.equals("")) {
////                String[] vel_new_lis = vel_new.split(",");
////                rve = new ReceiveVolEle();
////                for (int j = 0; j < vel_new_lis.length; j++) {
////                    switch (j) {
////                        case 1:
////                            rve.setIndx(Integer.parseInt(vel_new_lis[j]));
////                            rve.setCreateTime(DateUtils.parseDate());
////                            rve.setGropId(simpleUUID);
////                            Items items = findSelectItem();
////                            rve.setItemId(items.getId());
////                            break;
////
////                        case 7:
////                            rve.setTxv(vel_new_lis[j]);
////                            break;
////                        case 8:
////                            rve.setTxc(vel_new_lis[j]);
////                            break;
////
////                        case 9:
////                            rve.setRxv(vel_new_lis[j]);
////                            break;
////                    }
////
////                }
////                lis.add(rve);
////                queue1.enQueue(rve);
////                ReceiveVolEle rveDo = (ReceiveVolEle) queue1.deQueue();
////                //queue.clear();
////                if (rve != null && rve.getIndx() != null) {
////                    receiveVolEleService.save(rve);
////                }
////                receive_sta = true;
////            }
////
////        }
//    }
//}